package com.xckj.ibox.framework.net;

import android.util.Log;


import androidx.annotation.NonNull;

import com.xckj.ibox.global.ApiService;
import com.xckj.ibox.global.Constant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Author: ChenYao
 * @Describe: Retrofit管理
 * @Date: 2023/6/11 19:20
 */
public class RetrofitManager {

    private static volatile RetrofitManager instance;
    private final ApiService service;
    public final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    private RetrofitManager() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient httpClient = new OkHttpClient()
                .newBuilder().addInterceptor(new HeadIntercept())
                .addInterceptor(new HeadIntercept())
                .connectTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .addInterceptor(loggingInterceptor)
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @NonNull
                    @Override
                    public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        Log.e("OkHttp", "request:cookies.size" + cookies);
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder().client(httpClient)
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()).build();
        service = retrofit.create(ApiService.class);
    }

    public static RetrofitManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }

    public ApiService getService() {
        return service;
    }
}
